#include "LoginSignup.h"

//创建用户信息
struct User * CreateUser(char *name,char *pwd)
{
    struct User * user = (struct User *)malloc(sizeof(struct User));
    if(user == NULL)
    {
        printf("CreateUser malloc error!\n");
        return NULL;
    }
    user->name = name;
    user->pwd = pwd;
    return user;
}

//释放用户
void FreeUser(struct User * user)
{
    if(user!=NULL)
    {
        free(user);
        user->name = NULL;
        user->pwd = NULL;
    }
}

//判断注册的账号是否已经被注册
int IsEqualID(const char *FilePath,char *userName)
{
    FILE *file = fopen(FilePath, "r");
    if (file == NULL)
    {
        return false;
    }
    char line[15];
    while (fgets(line, sizeof(line), file))
    {
        char *name = strtok(line, "=");
        if (name != NULL && strcmp(name, userName) == 0)
        {
            fclose(file);
            return true;
        }
        memset(line,0,15);
    }

    fclose(file);
    return false;
}

//注册
int SignUp(char *name,char *pwd,const char *FilePath)
{
    //IsEqualID==true说明已经被注册
    if (IsEqualID(FilePath, name))
    {
        printf("该用户名已经被注册!\n");
        return 0;
    }
    int len = strlen(name) + strlen(pwd) + 1 + 1;
    char *userdata = NULL;
    userdata = (char *)malloc(sizeof(char) * len);
    if(userdata == NULL)
    {
        printf("userdata malloc error!\n");
        return false;
    }
    //将玩家的信息按照“账户=密码”的格式拼接起来存入到文件中
    strcpy(userdata,name);
    strcat(userdata,"=");
    strcat(userdata,pwd);
    //printf("%s\n",userdata);
    AppenedToFile(FilePath,userdata,len - 1);
    printf("注册成功!\n");
    free(userdata);
    return true;
}


//分割账户密码，并创建一个用户，将用户的结构体指针存入到链表中
void StrTok(ElementType element,DBL* list)
{
    char *str = (char *)element;
    char *userName = strtok(str,"=");
    char *pwd = strtok(NULL,"=");
    struct User* user = CreateUser(userName,pwd);
    DBInsertTail(list,user);
}

//登录
int Login(char *name,char *pwd,DBL *list)
{
    //将用户的信息从文件中读取出来存入链表，并开始遍历匹配输入的账号密码
    struct Node * TravelPoint = list->head;
    while (TravelPoint != NULL)
    {
        struct User* user = (struct User*)TravelPoint->data;
        if(strcmp(user->name,name) == 0 && strcmp(user->pwd,pwd) == 0)
        {
            printf("欢迎用户%s进入魔塔!\n",name);
            return true;
        }
        TravelPoint = TravelPoint->next;
    }
    printf("用户名或密码错误!\n");
    return false;
}


